package com.mingqijia.gassafety.job.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.Contacts;
import com.mingqijia.gassafety.db.entity.ConsumerDtuHistory;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.FieldTemplate;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.job.request.BindingPositionRequest;
import com.mingqijia.gassafety.job.request.ConsumerBindingRequest;
import com.mingqijia.gassafety.job.request.ConsumerListRequest;
import com.mingqijia.gassafety.job.response.CompanyListResponse;
import com.mingqijia.gassafety.job.response.ConsumerResponse;
import com.mingqijia.gassafety.job.response.VccUserRseponse;
import com.mingqijia.gassafety.job.service.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.ConsumerServiceStatusEnum;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-02-22
 */
@Slf4j
@Service
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements ConsumerService {
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    ConsumerMapper consumerMapper;
    @Autowired
    ConfigureHolder holder;
    @Autowired
    ContactsService contactsService;

    @Autowired
    FieldTemplateMapper fieldTemplateMapper;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    DtuAepMapper dtuAepMapper;
    @Autowired
    ConsumerDtuHistoryMapper consumerDtuHistoryMapper;
    @Autowired
    DtuBindingOrderMapper dtuBindingOrderMapper;
    @Autowired
    ConsumerServiceInfoService consumerServiceInfoService;
    @Autowired
    VccAuthoritiesProvider vccAuthoritiesProvider;
    @Autowired
    CompanyService companyService;
    @Autowired
    ConsumerLocationService consumerLocationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindingEquipment(ConsumerBindingRequest request) {
        log.info("安装工单完成------------开始绑定设备:{} ", JSONObject.toJSONString(request));
        String spId = request.getSpId();
        //确定是哪种模板调用
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        if (request.getBindChannel() ==null){
            request.setBindChannel(template.getTemplateType());
        }
        for (BindingPositionRequest positionRequest  : request.getImeiList()) {
            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
            consumerQueryWrapper.lambda().eq( Consumer::getId,request.getConsumerId() )
                    .eq( Consumer::getSpId,spId )
                    .eq( Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
            Consumer consumer = consumerMapper.selectOne( consumerQueryWrapper );

            String imei = positionRequest.getImei();
            QueryWrapper<Dtu> DtuWrapper = new QueryWrapper<>();
            DtuWrapper.lambda().eq( Dtu::getIMEI,imei )
                    .eq( Dtu::getIsDeleted,Constants.IS_DELETED_FALSE )
                    .eq( Dtu::getConsumerId,0 )
                    .eq( Dtu::getSpId,spId );
            List<Dtu> dtuList = equipmentService.list( DtuWrapper );
            if(CollectionUtil.isEmpty( dtuList )){
                throw new BizException( "该IMEI不存在或已绑定客户" );
            }
            //更新dtu
            Dtu dtu = new Dtu();
            dtu.setConsumerId( request.getConsumerId() );
            dtu.setSectorType(StringUtils.isEmpty(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
            //根据不同渠道更新设备的安装地址;
            if (BIND_CHANNEL_GAS == request.getBindChannel() || BIND_CHANNEL_MBP == request.getBindChannel()) {
                //报警器后台绑定, 此处同步客户的地址和经纬度
                //时刻助手绑定设备,安装地址在同步接口中更新
//                dtu.setInstallationAddress(consumer.getAddress());
                dtu.setPositionLat(consumer.getPositionLat());
                dtu.setPositionLon(consumer.getPositionLon());
            }
            dtu.setInstallationPosition(StringUtils.isEmpty(positionRequest.getInstallationPosition())? consumer.getAddress(): positionRequest.getInstallationPosition());
            equipmentService.update(dtu,DtuWrapper);   // 更新 主体的绑定
            List<String> imeiUpdateList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
            String now = DateUtil.now();
            dtuAepMapper.bindingEquipment(imeiUpdateList,spId,now);  //更新aep表开通时间,状态

            //对于控制器类型
            if ( dtuList.get( 0 ).getEquipmentType().equals( EquipmentType.GAS_ALARM_CONTROLLER.getCode())){
                QueryWrapper<Dtu> DtuWrapper1 = new QueryWrapper<>();
                DtuWrapper1.lambda().likeRight( Dtu::getIMEI,imei+"-" )  // 将 IMEI-  XX-XX的设备同时进行绑定;
                        .eq( Dtu::getIsDeleted,Constants.IS_DELETED_FALSE )
                        .eq( Dtu::getSpId,spId );
                dtuMapper.update( dtu, DtuWrapper1 );// 如果有 点型探测器, 更新绑定
            }

            //更新客户 设备数, 点位数
            //当前客户的点位数
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().like(Dtu::getIMEI , "-")
                    .eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq( Dtu::getIsDeleted,Constants.IS_DELETED_FALSE )
                    .eq( Dtu::getSpId,spId );
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            Consumer consumerNew = new Consumer();
            consumerNew.setEquipmentTotal( consumer.getEquipmentTotal()+1 );
            log.info( "设备:{}绑定, 客户id={}, 原点位数={}, 现点位数={}",imei,consumer.getId(),consumer.getPointTotal(),dtus.size() );
            consumerNew.setPointTotal( dtus.size());
            consumerMapper.update( consumerNew,consumerQueryWrapper );
            
            consumerLocationService.updateConsumerLocationDeviceNum(spId, request.getConsumerId());

            //绑定记录新增
            ConsumerDtuHistory history = new ConsumerDtuHistory();
            history.setId(null);
            history.setBindChannel(request.getBindChannel());
            history.setOutOrderCode(request.getOutOrderCode());
            history.setDeviceId(dtuList.get(0).getId());
            history.setEvent( 1 );
            history.setIMEI(imei);
            history.setConsumerId(consumer.getId());
            if (request.getBindChannel().equals(BIND_CHANNEL_MBP)){
                history.setOperationPersonCode("mbp");
                history.setOperationPersonName("mbp");
            }
            history.setRemark(Constants.STR_EMPTY);
            history.setSpId(request.getSpId());
            //当没有点型探测器被绑定时
            consumerDtuHistoryMapper.insert(history);
            //生成服务信息
            consumerServiceInfoService.addConsumerServiceInfo(positionRequest.getImei(),consumer.getIndustryType());
        }




    }

    @Override
    public PageUtil<ConsumerResponse> consumerList(ConsumerListRequest request) {
        String spId = request.getSpId();
        Page<Consumer> page =null;
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        if(CollectionUtil.isNotEmpty( request.getConsumerIdList() )){
            //勾选id查询
            queryWrapper.lambda().in( Consumer::getId,request.getConsumerIdList() )
                    .eq( Consumer::getIsDeleted, Constants.IS_DELETED_FALSE )
                    .eq( Consumer::getSpId,spId )
                    .orderByDesc( Consumer::getUpdatedAt );
        }else {
            boolean isServiceSelect = false;
            List<Integer> consumerIdList = new ArrayList<>();
            if (request.getServiceStatus() != null && ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(request.getServiceStatus()) != null) {
                isServiceSelect = true;
                QueryWrapper<ConsumerServiceInfo> consumerServiceInfoQueryWrapper = new QueryWrapper<>();
                if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_1.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().gt(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 30));
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_2.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().le(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 30))
                            .gt(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 7));
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_3.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().le(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 7))
                            .gt(ConsumerServiceInfo::getEndDate, DateUtils.today());
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_4.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().eq(ConsumerServiceInfo::getEndDate, DateUtils.today());
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_5.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().lt(ConsumerServiceInfo::getEndDate, DateUtils.today())
                            .ge(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), -7));
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_6.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().lt(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), -7));
                }
                consumerServiceInfoQueryWrapper.lambda().eq(ConsumerServiceInfo::getIsDeleted, IS_DELETED_FALSE)
                        .eq(ConsumerServiceInfo::getSpId, spId);
                List<ConsumerServiceInfo> consumerServiceInfoList = consumerServiceInfoService.list(consumerServiceInfoQueryWrapper);

                consumerIdList = consumerServiceInfoList.stream()
                        .map(ConsumerServiceInfo::getConsumerId).distinct().collect(Collectors.toList());
            }
            //是否存在 imei查询
            Dtu dtu = null;
            if (StringUtil.isNotEmpty(request.getImei())) {
                QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                        .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                dtu = dtuMapper.selectOne(dtuQueryWrapper);
                if (dtu != null && (!isServiceSelect || (isServiceSelect && consumerIdList.contains(dtu.getConsumerId())))) {
                    queryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId());
                }
                else {
                    queryWrapper.lambda().eq(Consumer::getId, null);
                }
            } else if (request.getServiceStatus() != null && ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(request.getServiceStatus()) != null) {
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(consumerIdList)) {
                    queryWrapper.lambda().in(Consumer::getId, consumerIdList);
                }
                else {
                    queryWrapper.lambda().eq(Consumer::getId, null);
                }
            }
            //是否存在电磁阀
            if (request.getHasValve() != null) {
                QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                dtuQueryWrapper.lambda().eq(Dtu::getIsDeleted, IS_DELETED_FALSE).eq(Dtu::getSpId, spId)
                        .ne(Dtu::getValveInfoId, 0);
                List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
                List<Integer> consumerLists = dtus.stream().map(Dtu::getConsumerId).collect(Collectors.toList());
                if ( !CollectionUtils.isEmpty(consumerLists)) {
                    if (request.getHasValve() == 0){
                        queryWrapper.lambda().notIn(Consumer::getId, consumerLists);
                    }else {
                        queryWrapper.lambda().in(Consumer::getId, consumerLists);
                    }
                } else {
                    if (request.getHasValve() == 1){
                        queryWrapper.lambda().eq(Consumer::getId, null);
                    }
                }
            }
            //常规查询,精准查询
            queryWrapper.lambda().eq( request.getConsumerName()!=null, Consumer::getName,request.getConsumerName() ) //客户名称
                    .eq(StringUtil.isNotEmpty(request.getCustName()), Consumer::getCustName, request.getCustName())           // 户名
                    .eq(StringUtil.isNotEmpty(request.getCustAddress()), Consumer::getCustAddress, request.getCustAddress())  //户址
                    .eq(StringUtil.isNotEmpty(request.getCustPhone()), Consumer::getCustPhone, request.getCustPhone())       //户主手机号
                    .eq(StringUtil.isNotEmpty(request.getSubsCode()), Consumer::getSubsCode, request.getSubsCode())//户号
                    .eq(StringUtil.isNotEmpty(request.getOrgCode()), Consumer::getOrgCode, request.getOrgCode()) //组织编码
                    .in( CollectionUtil.isNotEmpty( request.getIndustryType() ), Consumer::getIndustryType,request.getIndustryType() ) //行业类型多选
                    .eq( Consumer::getIsDeleted, Constants.IS_DELETED_FALSE )
                    .eq(StringUtil.isNotEmpty(request.getPhone()),Consumer::getPhone, request.getPhone() )
                    .eq(StringUtil.isNotEmpty(request.getMemberId()), Consumer::getMemberId, request.getMemberId())
                    .eq( Consumer::getSpId,spId )
                    .and(request.getHasLongitudeAndLatitude() != null && request.getHasLongitudeAndLatitude() == 1, lqw -> {
                        lqw.isNotNull(Consumer::getPositionLat).or().isNotNull(Consumer::getPositionLon);
                    })
                    .and(request.getHasLongitudeAndLatitude() != null && request.getHasLongitudeAndLatitude() == 0, lqw -> {
                        lqw.isNull(Consumer::getPositionLat).isNull(Consumer::getPositionLon);
                    })
                    .like(StringUtil.isNotEmpty(request.getConsumerName()), Consumer::getCustomerAddress, request.getConsumerName()) //客户地址
                    .orderByDesc( Consumer::getUpdatedAt );
            if(StringUtil.isNotEmpty(request.getCreateStartTime()) && StringUtil.isNotEmpty(request.getCreateEndTime())){
                Date startTime = DateUtil.parse(request.getCreateStartTime());
                Date endTime = DateUtil.endOfDay(DateUtil.parse(request.getCreateEndTime()));
                queryWrapper.lambda().between(Consumer::getCreatedAt, startTime,endTime);
            }

            page = PageHelper.startPage( request.getPage(), request.getPageSize() );
        }
        List<Consumer> consumerList = consumerMapper.selectList( queryWrapper );
        List<String> spIds = new ArrayList<>();
        spIds.add(spId);
        //查询组织架构名称
        List<CompanyListResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyListResponse::getSpId, CompanyListResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        //根据行业类型获得名字
        List<DictionaryItemRespDTO> industryType = holder.getDictionaryByKey( "industry_type" ,spId);
        ArrayList<ConsumerResponse> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty( consumerList )){
            //获得客户id集合
            List<Integer> ids = consumerList.stream().map( Consumer::getId ).collect( Collectors.toList() );
            log.info( "客户id集合: {}",ids.toString() );
            //获取每个客户的最高级联系人
            List<Contacts> contactsList = contactsService.listByIds( ids,spId );
            for (Consumer consumer : consumerList) {
                ConsumerResponse consumerResponse = new ConsumerResponse();
                BeanUtil.copyProperties( consumer, consumerResponse );
                consumerResponse.setConsumerId(consumer.getId());
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(consumer.getOrgCode()) && orgSubsCodeMap.containsKey(consumer.getOrgCode())) {
                    consumerResponse.setCompanyName(orgSubsCodeMap.get(consumer.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(consumer.getSpId())) {
                        consumerResponse.setCompanyName(companyNameMap.get(consumer.getSpId()));
                    }
                }
                for (DictionaryItemRespDTO dto : industryType) {
                    if (dto.getValue().equals( consumerResponse.getIndustryType() )){
                        consumerResponse.setIndustryName( dto.getName() );
                    }
                }
                for (Contacts contacts : contactsList) {
                    //关联的联系人数据
                    if (consumer.getId().equals( contacts.getConsumerId() )){
                        consumerResponse.setContactsName( contacts.getName() );
                        consumerResponse.setContactsTelephone( contacts.getTelephone() );
                    }
                }
                consumerResponse.setPosition(consumer.getPositionLon() + "," + consumer.getPositionLat());

                //客户来源
                consumerResponse.setSource(consumer.getSource() == 0 ? CONSUMER_SOURCE_SYSTEM:CONSUMER_SOURCE_ASST);
                list.add( consumerResponse );
            }
        }

        PageUtil<ConsumerResponse> pageUtil = new PageUtil<>();
        if (page!=null){
            pageUtil.setPage( page.getPages() );
            pageUtil.setPageSize( page.getPageSize() );
            pageUtil.setTotal( page.getTotal() );
        }else {
            //非分页列表时,置0
            pageUtil.setPage( 0 );
            pageUtil.setPageSize( 0 );
            pageUtil.setTotal( request.getConsumerIdList().size() );
        }
        pageUtil.setList( list );
        return pageUtil;
    }

    @Override
    public Map<String, Object> getInfoByImei(String iMEI, String spId) {
        //判断spId所属模板类型
        Integer templateType = fieldTemplateMapper.getTypeBySpId(spId).getTemplateType();
        log.info("设备imei:{},属于模板:{}企业",iMEI,templateType);
        Map<String, Object> map = new HashMap<>();
        if (templateType.equals(BIND_CHANNEL_GAS) ){
            map =  consumerMapper.gasGasInfoByImei(iMEI,spId);
        }else if (templateType.equals(BIND_CHANNEL_ASST)) {
            map =  dtuBindingOrderMapper.gasAsstInfoByImei(iMEI,spId);

        }
        return map;
    }

    /**
     * 更新客户
     * @param subsCode
     */
    @Override
    public void updateStatusByCode(String subsCode) {
        consumerMapper.updateStatusByCode(subsCode);
    }

    @Override
    public VccUserRseponse getVccUser(String subsCode,String spId,String  orgCode){
        log.info("getVccUser-params:{},{}",subsCode,spId);
        VccUserRseponse response = new VccUserRseponse();
        try {
            cn.hutool.json.JSONObject vccUser =null;
            if (org.apache.commons.lang3.StringUtils.isBlank(orgCode)){
                List<String>  orgCodes = companyService.getOrgCodeBySubsCode(org.apache.commons.lang3.StringUtils.isBlank(spId)?ApplicationUtils.getWorkingSpId():spId);
                log.info("orgCodes:" + orgCodes);
                for (String code : orgCodes) {
                    try {
                        vccUser = vccAuthoritiesProvider.getVccUser(code, subsCode);
                        log.info("getVccUser-vccUser:{}",JSONObject.toJSON(vccUser));
                    } catch (Exception e) {
                        log.error("getVccUser-error:{}",e);
                    }
                    if (vccUser != null) break;
                }
            }else{
                vccUser = vccAuthoritiesProvider.getVccUser(orgCode, subsCode);

            }

            if (vccUser == null) {
                return null;
            }
            log.info("vccUser :{}", vccUser.toString());
            response.setCustName(vccUser.get("name").toString());
            response.setSubsCode(vccUser.get("subsCode").toString());
            response.setCustPhone(vccUser.get("phone").toString());
            response.setCustAddress(vccUser.get("displayAddr").toString());
            response.setCustType(vccUser.get("subsType").toString());
            response.setCustStatus(vccUser.get("state").toString());
        } catch (GlobalAuthenticationException e) {
            log.info("获取vcc户表信息失败, 户号:{}", subsCode);
            return null;
        }
        return response;
    }

    public VccUserRseponse getVccUserC(String subsCode,String spId,String  orgCode) {
        log.info("getVccUser-params:{},{}",subsCode,spId);
        VccUserRseponse response = new VccUserRseponse();
        try {
            cn.hutool.json.JSONObject vccUser =null;
            if (org.apache.commons.lang3.StringUtils.isBlank(orgCode)){
                List<String>  orgCodes = companyService.getOrgCodeBySubsCode(org.apache.commons.lang3.StringUtils.isBlank(spId)?ApplicationUtils.getWorkingSpId():spId);
                log.info("orgCodes:" + orgCodes);
                for (String code : orgCodes) {
                        vccUser = vccAuthoritiesProvider.getVccUserC(code, subsCode);
                        log.info("getVccUser-vccUser:{}",JSONObject.toJSON(vccUser));
                    if (vccUser != null) break;
                }
            }else{
                vccUser = vccAuthoritiesProvider.getVccUserC(orgCode, subsCode);

            }

            if (vccUser == null) {
                return null;
            }
            log.info("vccUser :{}", vccUser.toString());
            response.setCustName(vccUser.get("name").toString());
            response.setSubsCode(vccUser.get("subsCode").toString());
            response.setCustPhone(vccUser.get("phone").toString());
            response.setCustAddress(vccUser.get("displayAddr").toString());
            response.setCustType(vccUser.get("subsType").toString());
            response.setCustStatus(vccUser.get("state").toString());
        } catch (GlobalAuthenticationException e) {
            log.info("获取vcc户表信息失败, 户号:{}", subsCode);
            return null;
        }
        return response;
    }

    @Override
    public String getConsumerRelateSpId(Integer consumerId, String originSpId) {
        String spId = originSpId;
        try {
            if (null == consumerId || consumerId <= 0) {
                return spId;
            }
            Consumer consumer = consumerMapper.selectById(consumerId);
            log.info("getConsumerRelateSpId consumer:{}", JSONObject.toJSONString(consumer));
            if (null != consumer && !StringUtils.isEmpty(consumer.getOrgCode())) {
                LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CompanyEntry::getCode, consumer.getOrgCode());
                queryWrapper.eq(CompanyEntry::getIsDeleted, false);
                List<CompanyEntry> companyEntryList = companyService.list(queryWrapper);
                if (null != companyEntryList && !companyEntryList.isEmpty()) {
                    spId = companyEntryList.get(0).getId();
                    log.info("getConsumerRelateSpId spId change:{}", spId);
                }
            }
        }catch (Exception e){
            log.error("getConsumerRelateSpId error:",e);
        }
        return spId;
    }
}
